﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.Web.WebPages;

namespace MTO.Framework.Web.Mvc.Html
{
    public static class ScriptExtensions
    {
        private const string SCRIPTBLOCK_BUILDER = "ScriptBlockBuilder";

        /// <summary>
        /// Sert à déclarer des scripts clients dans les pages web View et PartialView. Chaque déclaration est
        /// cumulative.
        /// </summary>
        /// <param name="htmlHelper"></param>
        /// <param name="template"></param>
        /// <returns></returns>
        public static MvcHtmlString ScriptBlock(this HtmlHelper htmlHelper, Func<dynamic, HelperResult> template)
        {
            var context = htmlHelper.ViewContext.HttpContext;

            if (!context.Request.IsAjaxRequest())
            {
                var scriptBuilder = context.Items[SCRIPTBLOCK_BUILDER] as StringBuilder ?? new StringBuilder();

                scriptBuilder.Append(template(null).ToHtmlString());
                context.Items[SCRIPTBLOCK_BUILDER] = scriptBuilder;

                return new MvcHtmlString(string.Empty);
            }

            return new MvcHtmlString(template(null).ToHtmlString());
        }

        // Sert à écrire toutes les déclarations scripts qui ont été définies à l'aide de ScriptBlock.
        public static MvcHtmlString RenderScriptBlocks(this HtmlHelper htmlHelper)
        {
            var scriptBuilder = htmlHelper.ViewContext.HttpContext.Items[SCRIPTBLOCK_BUILDER] as StringBuilder ?? new StringBuilder();

            return new MvcHtmlString(scriptBuilder.ToString());
        }
    }
}
